package ext.generic.part;

import java.util.*;

import wt.fc.WTReference;

import wt.org.WTUser;

import wt.session.SessionHelper;

import wt.util.WTException;

import wt.vc.Iterated;

import com.ptc.core.ui.validation.DefaultUIComponentValidator;
import com.ptc.core.ui.validation.UIValidationCriteria;
import com.ptc.core.ui.validation.UIValidationKey;
import com.ptc.core.ui.validation.UIValidationResult;
import com.ptc.core.ui.validation.UIValidationResultSet;
import com.ptc.core.ui.validation.UIValidationStatus;

/**
 *该类用于”清除流程信息“入口的校验；
 */
public class ClearHistoricalIBAValidator extends DefaultUIComponentValidator
{
    /**
     *校验条件：当前对象必须是”版本控制“的对象，且是最新小版本；另外，当前用户必须是系统管理员
     * @param uivalidationkey
     * @param uivalidationcriteria
     * @param locale
     * @return
     * @throws WTException
     */
    public UIValidationResultSet performFullPreValidation(UIValidationKey uivalidationkey, UIValidationCriteria uivalidationcriteria, Locale locale) throws WTException
    {
        UIValidationStatus uivalidationstatus = UIValidationStatus.HIDDEN;
        UIValidationResultSet uivresultSet = new UIValidationResultSet();
        boolean enable = false;
        if (uivalidationcriteria != null && uivalidationcriteria.getContextObject() != null)
        {
            WTReference wtreference = uivalidationcriteria.getContextObject();
            wt.fc.Persistable persistable = wtreference.getObject();
            if (persistable != null)
            {
                if ((persistable instanceof Iterated) && ((Iterated) persistable).isLatestIteration())
                {
                    WTUser curUser = (WTUser) SessionHelper.manager.getPrincipal();
                    if (isAdministrator(curUser))
                    {
                        enable = true;
                    }
                }
            }
        }
        if (enable)
        {
            uivresultSet.addResult(new UIValidationResult(uivalidationkey, UIValidationStatus.ENABLED));
        }
        else
        {
            uivresultSet.addResult(new UIValidationResult(uivalidationkey, UIValidationStatus.HIDDEN));
        }
        return uivresultSet;
    }

    /**
     *当前用户是否系统管理员
     */
    private static boolean isAdministrator(WTUser user) throws WTException
    {
        WTUser curUser = (WTUser) SessionHelper.manager.getPrincipal();
        Enumeration eGroupName = curUser.parentGroupNames();
        while (eGroupName.hasMoreElements())
        {
            String groupName = (String) eGroupName.nextElement();
            if (groupName.equalsIgnoreCase("Administrators"))
            {
                return true;
            }
        }
        return false;
    }
}

